﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TBlog.Web.Service;
using TBlog.Web.ViewModel;

namespace TBlog.Web.Controllers
{
    public class ManageController : Controller
    {
        //
        // GET: /Manage/
        readonly IManageService _mservice;
        public ManageController(IManageService mservice)
        {
            _mservice = mservice;
        }
        public ActionResult Login()
        {
            //Session["PwdErrorCount"] = "3";
            return View();
        }
        [ValidateAntiForgeryToken]
        [AllowAnonymous]
        [HttpPost]
        public JsonResult Login(Manage model)
        {
            int errorcount = Session["PwdErrorCount"] == null ? 0 : Convert.ToInt32(Session["PwdErrorCount"]);

            //验证密码是否正确
            if (!string.IsNullOrWhiteSpace(model.ValidCode))
            {
                if (model.ValidCode == Session["VerifyCode"].ToString())
                    return Json(_mservice.GetJsonMessage(false, "", "验证码错误，请重新输入"));
            }
            var res = _mservice.Valid(model.UserName, model.PassWord);
            if (!res)
            {
                errorcount += 1;
                Session["PwdErrorCount"] = errorcount;
                return Json(_mservice.GetJsonMessage(false, "", "出现错误"), JsonRequestBehavior.DenyGet);
            }
            Session["PwdErrorCount"] = 0;
            return Json(_mservice.GetJsonMessage(true, "", "正常"));

        }

        public JsonResult LoginOut()
        {
            return Json("");
        }

        /// <summary>
        /// 生成验证码
        /// </summary>
        /// <returns></returns>
        public ActionResult GetValidateCode()
        {
            byte[] bytes = _mservice.GetValidate(5);
            return File(bytes, @"image/jpeg");
        }
    }
}
